package de.rac.vaadin.framework.ui;
/*******************************************************************************
 * Web design data view block (base class: the basic functionality includes 
 * a table view, a create/edit/delete menu, an edit field form) <br>
 * @author Volodymyr Dobryvechir (dobrivecher@yahoo.com)
 * @version 0.2 31.05.2012  <br>
 ******************************************************************************/
import java.util.ArrayList;
import java.util.LinkedHashMap;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.ui.*;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Table.HeaderClickEvent;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.themes.Runo;
import com.oros.db.*;
public class GeneralWindow extends VerticalLayout {
    
	private static final long serialVersionUID = 2348994061393412494L;
	protected MenuBar menuBar;
	protected MenuBar.MenuItem mAdd;
	protected MenuBar.MenuItem mEdit;
	protected MenuBar.MenuItem mDelete;
	protected MenuBar.MenuItem mRefresh;
    protected HorizontalSplitPanel tableAndFormLayout;	
    protected TableSource sourceData;
    protected Object newEditObjectId;
    protected Table viewTable;
    protected Panel newEditPanel,scrollableTableAndFormPanel;
    protected Form newEditForm;
    protected HorizontalLayout editButtonLayout,menuLayout;
    private boolean isBuildRequired;
    protected VerticalLayout newEditPanelLayout;
    protected Button bApply,bCancel;
    protected boolean isNewDocumentAdded;
    protected HorizontalLayout filterBar;
    protected VerticalLayout leftSideLayout;
    protected String editFieldWidth;
    protected TextField[] filterTextFields;
    protected boolean isShowAuthorized,isReplacingMessageHanging;
    protected ArrayList<Component> rootComponents;
    protected Component menuLevel_RightAdjusted_AdditionalComponent;
    protected boolean lastTimeEditFormWasAttached;
    protected ConfirmDialog detachedNewEditDialog;
    protected boolean containerLevelSorting = false;
    protected LinkedHashMap <MenuBar.MenuItem,String> lingMenuMap=new LinkedHashMap<MenuBar.MenuItem,String>();
	protected void enableFormPanel() throws Exception
    {
		
        if (mEdit!=null) mEdit.setEnabled(false);
    	if (mDelete!=null) mDelete.setEnabled(false);
    	if (mAdd!=null) mAdd.setEnabled(false);
    	if (mRefresh!=null) mRefresh.setEnabled(false);
        newEditForm.setItemDataSource(sourceData.getViewTable().getItem(newEditObjectId));
        if (sourceData.isEditFormDetached())
        {
        	if (lastTimeEditFormWasAttached)
        	{
        		tableAndFormLayout.removeComponent(newEditPanel);
        		lastTimeEditFormWasAttached=false;
        		
        	}
        	newEditPanel.setVisible(true);
        	newEditPanel.setImmediate(true);
        	getWindow().addWindow(
        			detachedNewEditDialog=new ConfirmDialog("",
                     newEditPanel,
        			 null,
        			 null,
        			new ConfirmDialog.Callback() {
						
						private static final long serialVersionUID = 5053817083273511190L;
                        
                        
						@Override
						public void onDialogResult(boolean resultIsYes) {
							
							if (resultIsYes){
								try {
									System.out.println("Ja");
									//sourceData.getViewTable().removeItem(newEditObjectId);
									//sourceData.getViewTable().commit();
									//sourceData.getViewTable().refresh();
									//viewTable.refreshRowCache();
				                } catch (Exception e) {
				                	e.printStackTrace();
				                	getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
				                }
								
							}
							else
							{
								ensureDisableFormPanel();
							}
							
						}


						@Override
						public boolean validateFinish() {
							return true;
						}
					},sourceData.getDesignEditFormDetachedWidth(),sourceData.getDesignEditFormDetachedHeight()
        		));
        }
        else
        {
        	if (!lastTimeEditFormWasAttached)
        	{
        		lastTimeEditFormWasAttached=true;
        		tableAndFormLayout.addComponent(newEditPanel);
        	}
        	newEditPanel.setVisible(true);
        }
    }
	public void ensureDisableFormPanel()
	{
		if (newEditPanel!=null && newEditPanel.isVisible())
		{
			try {
				sourceData.getViewTable().rollback();
	        } catch (Exception e) {
	        	getWindow().showNotification(menuCommand.messageServerError, e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
	        }
		}
		disableFormPanel();
	}
	protected void disableEnableMainParts(boolean editReady)
	{
    	if (scrollableTableAndFormPanel!=null) scrollableTableAndFormPanel.setVisible(editReady);
    	if (menuBar!=null) menuBar.setVisible(editReady);		
	}
    protected void disableFormPanel()
    {
    	if (detachedNewEditDialog!=null)
    	{
    		detachedNewEditDialog.closeWindow();
    		detachedNewEditDialog=null;
    	}
       	boolean editReady = sourceData.isFormReadyForNewEditDelete();
       	disableEnableMainParts(editReady);
     	if (newEditPanel==null) return;
    	newEditPanel.setVisible(false);
 
    	if (viewTable.getValue()==null)
    	{
    		Object itemId = sourceData.getViewTable().firstItemId();
    		if (itemId!=null) viewTable.setValue(itemId);
    	}
    	if (mEdit!=null){
    		mEdit.setEnabled(editReady);
    	} 
    	if (mDelete!=null) {
    		mDelete.setEnabled(editReady);
    	}
    	if (mRefresh!=null)
    	{
    		mRefresh.setEnabled(true);
    	}
    	if (mAdd!=null)
    	{
    	    mAdd.setEnabled(editReady);
    	}
    	newEditObjectId=null;
        if (newEditForm!=null) newEditForm.setItemDataSource(null);
    }

    
    
    protected GeneralWindowCommand menuCommand=getGeneralWindowCommand();
    protected GeneralWindowCommand getGeneralWindowCommand()
    {
    	return new GeneralWindowCommand();
    }
	protected Object createNewRowItem(AETableContainer table) throws Exception
	{
		newEditObjectId=table.addItem();
		return newEditObjectId;
	}
	protected void setNewEditItemField(String columnName,Object value)
	{
		if (newEditObjectId==null) return;
        sourceData.getViewTable().setPropertiesOfItem(newEditObjectId, columnName, value);
	}
    public class GeneralWindowCommand implements Command 
    {
		private static final long serialVersionUID = 2164852947325709550L;
		public static final String menuNew = "New";
		public static final String menuEdit = "Edit";
		public static final String menuDelete = "Delete";
		public static final String menuRefresh = "Refresh";
		public final int COMMAND_NEW = 1;
		public final int COMMAND_EDIT = 2;
		public final int COMMAND_DELETE = 3;
		public final int COMMAND_REFRESH = 4;
		public String messageNew,messageEdit,messageDelete,messageRefresh,messageUnknowMenuCommand,
		    messageAddingNewRecord,messageServerOverloaded,messageRecordDeleting,messageOk,messageCancel,
		    messageServerError,messageEditingRecord,messageNoRecordIsChosen,messageRecordWillBeRemoved,
		    messageFieldMustBeUnique,messageYouAreNotAuthorizedForThisForm;
		public int lastCommand;
		public void setNewEditPanelHeader(int command)
		{
			lastCommand = command;
			renewNewEditPanelHeader();
		}
		public void renewNewEditPanelHeader()
		{
			switch(lastCommand)
			{
			case COMMAND_NEW:
				newEditPanel.setCaption(messageAddingNewRecord);
				break;
			case COMMAND_EDIT:
				newEditPanel.setCaption(messageEditingRecord);
				break;
			}
		}
		public void loadLanguageData(ResourcePool resource)
		{
			messageNew = resource.getTranslation(menuNew);
			messageDelete = resource.getTranslation(menuDelete);
			messageEdit = resource.getTranslation(menuEdit);
			messageRefresh = resource.getTranslation(menuRefresh);
			messageUnknowMenuCommand = resource.getTranslation("UnknownMenuCommand");
			messageServerOverloaded = resource.getTranslation("ServerOverloaded");
			messageServerError=resource.getTranslation("ServerError");
			messageAddingNewRecord = resource.getTranslation("table_AddingNewRecord");		
			messageEditingRecord=resource.getTranslation("table_EditingRecord");
			messageNoRecordIsChosen=resource.getTranslation("table_NoRecordIsChosen");
			messageRecordDeleting = resource.getTranslation("table_RecordDeleting");
			messageRecordWillBeRemoved=resource.getTranslation("table_RecordWillBeRemoved");
			messageFieldMustBeUnique=resource.getTranslation("table_FieldMustBeUnique");
			messageOk = resource.getTranslation("Ok");
		    messageCancel = resource.getTranslation("Cancel");
		    messageYouAreNotAuthorizedForThisForm = resource.getTranslation("YouAreNotAuthorizedForThisForm");
		}
		public void handleOtherMenuCommands(MenuItem selectedItem,String commandName) throws Exception
		{
			throw new Exception(messageUnknowMenuCommand+": "+commandName);
		}

		public void menuSelected(MenuItem selectedItem) {
			AETableContainer table; 
			int command=0;
			try {
				String commandName=selectedItem.getText();
				if (selectedItem==mAdd) command=COMMAND_NEW;
				else if (selectedItem==mEdit) command=COMMAND_EDIT;
				else if (selectedItem==mDelete) command=COMMAND_DELETE;
				else if (selectedItem==mRefresh) command=COMMAND_REFRESH;
				if (command==0) 
					{
					   handleOtherMenuCommands(selectedItem,commandName);
					   return;
					}
				table = sourceData.getViewTable();
        		table.rollback();
			} catch (Exception e) {
				getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
            	return;
            }
			newEditObjectId = viewTable.getValue();
            if (command==COMMAND_NEW){
            	setNewEditPanelHeader(COMMAND_NEW);
            	isNewDocumentAdded = true;
            	try
            	{
      
            	  newEditObjectId=createNewRowItem(table);
            	  if (newEditObjectId==null) 
            	  {
	                	getWindow().showNotification(messageServerOverloaded, Notification.TYPE_ERROR_MESSAGE);
	                	disableFormPanel();
            	  }
            	  else
            	  {
                	  enableFormPanel();
            		  //dbHelp.views.getDocumentViewContainer().setPropertiesOfItem(newEditDocumentId, "docrights.right", DocumentView.DOC_RIGHT_CREATOR);
            	  }
            	}
            	catch(Exception e)
            	{
            		e.printStackTrace();
                	getWindow().showNotification(messageServerError,e.getMessage(),Notification.TYPE_ERROR_MESSAGE);
                	disableFormPanel();
            	}
            }else if (command==COMMAND_EDIT) {
            	setNewEditPanelHeader(COMMAND_EDIT);
            	isNewDocumentAdded = false;
    			if (newEditObjectId==null)
    			{
                	getWindow().showNotification(messageNoRecordIsChosen, Notification.TYPE_ERROR_MESSAGE);
                	disableFormPanel();
                	return;
    			}

            	try
            	{
                	enableFormPanel();
            	}
            	catch(Exception e)
            	{
            		disableFormPanel();
            		
            	}
            } else if (command==COMMAND_REFRESH)
            {
				try {
					sourceData.getViewTable().rollback();
                } catch (Exception e) {
                	e.printStackTrace();
                	getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
                }
            }
            else if (command==COMMAND_DELETE){
    			if (newEditObjectId==null)
    			{
                	getWindow().showNotification(messageNoRecordIsChosen, Notification.TYPE_ERROR_MESSAGE);
                	return;
    			}
            	getWindow().addWindow(new ConfirmDialog(messageRecordDeleting,
            			messageRecordWillBeRemoved,
            			messageOk,
            			messageCancel,
            			new ConfirmDialog.Callback() {
							
							private static final long serialVersionUID = 5053817083273511190L;
                            
                            
							@Override
							public void onDialogResult(boolean resultIsYes) {
								
								if (resultIsYes){
					                viewTable.select(null);
									try {
										sourceData.getViewTable().removeItem(newEditObjectId);
										sourceData.getViewTable().commit();
										sourceData.getViewTable().refresh();
										viewTable.refreshRowCache();
					                } catch (Exception e) {
					                	e.printStackTrace();
					                	getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					                }
									
								}
								
							}


							@Override
							public boolean validateFinish() {
								return true;
							}
						},null,null
            		));
            };
        }
    };

    
    public GeneralWindow()
    {
	    isBuildRequired = true;
    }
    public void setSourceData(TableSource sourceData)
    {
        this.sourceData = sourceData;
    }
    public void activate() throws Exception
    {
    	if (isBuildRequired) rebuild(); 
    	else refresh();
    }
    public boolean notifyOfLocaleChange()
    {
    	if (isBuildRequired) return false;
    	ResourcePool resource = sourceData.getActiveSpecificResource();
    	menuCommand.loadLanguageData(resource);
    	for(MenuBar.MenuItem item:lingMenuMap.keySet())
    	{
    		String word = lingMenuMap.get(item);
    		if (word!=null)
    		{
    			String translation = resource.getTranslation(word);
    			item.setText(translation);
    		}
    	}
    	changeLocaleForNewEditPanelForm(resource,newEditPanel!=null && newEditPanel.isVisible());
    	if (newEditPanel!=null)
    	{
    		changeLocaleForNewEditPanel(resource);
    	}
    	if (viewTable!=null)
    	{
    		changeLocaleForViewTableColumnTitles(resource);
    		changeLocaleForViewTable(resource);
    		changeLocaleForViewTableFilter(resource);    		
    	}
    	return true;
    }

    protected void changeLocaleForViewTable(ResourcePool resource)
    {
    	
    	if (sourceData.getViewTable().applyTranslation(resource))
    	{
    		sourceData.getViewTable().fireContentsChange();
    	}
    }
    protected void changeLocaleForViewTableFilter(ResourcePool resource)
    {
    	if (filterTextFields==null) return;
		String[] visibleCols = sourceData.getTranslatedViewColumnHeaders(); 
		int ncols = visibleCols==null?0:visibleCols.length;
		if (filterTextFields.length!=ncols) return;
		for (int i=0;i<ncols;i++) 
		{ 
			TextField sf = filterTextFields[i]; 
			String pn = visibleCols[i];
			if (sf!=null && pn!=null)
			    sf.setInputPrompt(pn); 
		}
    }
    protected void changeLocaleForViewTableColumnTitles(ResourcePool resource)
    {
    	viewTable.setColumnHeaders(sourceData.getTranslatedViewColumnHeaders());
    }
    protected void setCaptionsForNewEditPanelButtons(ResourcePool resource)
    {
    	if (bApply!=null)
    	  bApply.setCaption(resource.getTranslation("Apply"));
    	if (bCancel!=null)
		  bCancel.setCaption(resource.getTranslation("Cancel"));
    }
    protected void changeLocaleForNewEditPanelHeader(ResourcePool resource)
    {
    	if (menuCommand!=null) menuCommand.renewNewEditPanelHeader();
    }
    protected void changeLocaleForNewEditPanelForm(ResourcePool resource,boolean activeEdit)
    {
    	sourceData.updateLocaleInfoOfEditFormFields(resource, activeEdit);
    }
    
    protected void changeLocaleForNewEditPanel(ResourcePool resource)
    {
    	setCaptionsForNewEditPanelButtons(resource);
    	changeLocaleForNewEditPanelHeader(resource);
    }
    protected void showReplacingMessage(String message)
    {
    	Label label = new Label(message);
    	this.addComponent(label);
    }
    public void setReplacingMessage(String message)
    {
    	isReplacingMessageHanging=true;
    	this.removeAllComponents();
    	showReplacingMessage(message);
    }
    protected void revokeReplacingMessage_Internal()
    {
    	this.removeAllComponents();
    	for(Component c:rootComponents)
    	{
    		this.addComponent(c);
    	}
    	isReplacingMessageHanging=false;
    }
    public void revokeReplacingMessage()
    {
    	if (isReplacingMessageHanging) validateRights();
    }
    public void validateRights()
    {
    	if (isBuildRequired) return;
    	if (!sourceData.getReadAllowed())
    	{
    		setReplacingMessage(menuCommand.messageYouAreNotAuthorizedForThisForm);
    		isShowAuthorized=false;
    	}
    	else
    	{
    		if (!isShowAuthorized)
    		{
    			revokeReplacingMessage_Internal();
    			isShowAuthorized=true;
    		}
    	}
    }
    protected void refresh() throws Exception
    {
    	if (sourceData.getViewTable()!=null)
    	    sourceData.getViewTable().refresh();
    }
    protected void rebuild() throws Exception
    {
    	isBuildRequired = false;
	    rootComponents = new ArrayList<Component>();
		ResourcePool resource = initResourceParameters();
		sourceData.viewTableInit();
        initMainWindow(resource);
        isShowAuthorized=sourceData.getReadAllowed();
		createMainWindow(resource);
        isReplacingMessageHanging=!isShowAuthorized;
		if (isReplacingMessageHanging) showReplacingMessage(menuCommand.messageYouAreNotAuthorizedForThisForm);
    }
    protected void createMainWindow(ResourcePool resource) throws Exception
    {
		createMenuLayout(resource);
		createScrollableTableAndFormPanel(resource);
		disableFormPanel();
    }
    protected void initMainWindow(ResourcePool resource) throws Exception
    {
    	this.setImmediate(false);
    	this.setWidth("100%");
    	this.setHeight("100%");
		setMargin(false);
		setSpacing(true);
    }
    protected ResourcePool initResourceParameters() throws Exception
    {
		ResourcePool resource = sourceData.getActiveSpecificResource();
		menuCommand.loadLanguageData(resource);
		editFieldWidth = resource.getDesignDefinition("general_window_edit_field_width", "200px");	
        return resource;    	
    }
    protected void createScrollableTableAndFormPanel(ResourcePool resource) throws Exception
    {
		scrollableTableAndFormPanel = new Panel();
		scrollableTableAndFormPanel.setScrollable(true);
		scrollableTableAndFormPanel.setImmediate(true);
		scrollableTableAndFormPanel.setHeight(sourceData.getDesignScrollableTableHeight());
	    rootComponents.add(scrollableTableAndFormPanel);
        if (isShowAuthorized) this.addComponent(scrollableTableAndFormPanel);
		createTableAndFormLayout(resource);	
    }
    protected void createTableAndFormLayout(ResourcePool resource) throws Exception
    {
		tableAndFormLayout = new HorizontalSplitPanel();
		tableAndFormLayout.setImmediate(false);

		tableAndFormLayout.setMargin(false);
		//tableAndFormLayout.setSpacing(true);
		tableAndFormLayout.setHeight("100%");
		String general_window_view_table_width=resource.getDesignDefinition("general_window_view_table_width_pixels", "550");
		if (sourceData.isEditFormDetached())
			tableAndFormLayout.setSplitPosition(100, HorizontalSplitPanel.UNITS_PERCENTAGE);
		else
		   tableAndFormLayout.setSplitPosition(Integer.parseInt(general_window_view_table_width), HorizontalSplitPanel.UNITS_PIXELS); //.setExpandRatio(leftSideLayout, 1.0f);
	    tableAndFormLayout.setHeight("100%");
	    tableAndFormLayout.setWidth("100%"); //.setSizeUndefined();
		scrollableTableAndFormPanel.setContent(tableAndFormLayout);
		createLeftSideLayout(resource);
		createNewEditPanel(resource);
    }
    protected void createNewEditPanel(ResourcePool resource) throws Exception
    {
		newEditPanel = new Panel();
		
		if (sourceData.isEditFormDetached())
		{
			newEditPanel.setVisible(true);
			newEditPanel.setImmediate(true);
			lastTimeEditFormWasAttached=false;
		}
		else
		{
			newEditPanel.setVisible(false);
			newEditPanel.setImmediate(false);
			tableAndFormLayout.addComponent(newEditPanel);
			lastTimeEditFormWasAttached=true;
		}
		createNewEditPanelLayout(resource);
    }
    protected void createNewEditPanelLayout(ResourcePool resource) throws Exception
    {
		newEditPanelLayout = new VerticalLayout();
		newEditPanelLayout.setImmediate(false);
		newEditPanelLayout.setMargin(true);
		newEditPanel.setContent(newEditPanelLayout);
		createNewEditForm(resource);
    }

    protected void createLeftSideLayout(ResourcePool resource) throws Exception
    {
		leftSideLayout = new VerticalLayout();
		leftSideLayout.setSizeFull();
		leftSideLayout.setImmediate(false);
	    tableAndFormLayout.addComponent(leftSideLayout);
	    createViewTable(resource);
		addTextFiltersForEachColumn(resource);
    }
    protected void addMenuBarItemsAtBeginning()
    {
    	
    }
    protected void addMenuBarItemsAtEnd()
    {
    	
    }

    protected void createMenuBar(ResourcePool resource,boolean forced) throws Exception
    {
		if (sourceData.getWriteAllowed() || forced)
		{
	        menuBar = new MenuBar();
	        menuBar.setImmediate(true);
	        boolean editReady = sourceData.isFormReadyForNewEditDelete();
	        addMenuBarItemsAtBeginning();
			if (sourceData.getWriteAllowed() || sourceData.isRefreshButtonPresent())
			{
		       boolean formPresent=sourceData.getEditFormFieldAmount()>0;
		       if (sourceData.getCreateAllowed() && formPresent)
		       {
		            mAdd = menuBar.addItem(menuCommand.messageNew, menuCommand);
		            lingMenuMap.put(mAdd,GeneralWindowCommand.menuNew);
		            mAdd.setEnabled(editReady);
		       } else System.out.println(sourceData.getViewTable()+" create allowed: "+sourceData.getCreateAllowed());
		       if (formPresent)
		       {
		          mEdit = menuBar.addItem(menuCommand.messageEdit, menuCommand);
		          lingMenuMap.put(mEdit, GeneralWindowCommand.menuEdit);
		          mEdit.setEnabled(editReady);
		       }
		       if (sourceData.getCreateAllowed())
		       {
		          mDelete = menuBar.addItem(menuCommand.messageDelete, menuCommand);
		          lingMenuMap.put(mDelete, GeneralWindowCommand.menuDelete);
		          mDelete.setEnabled(editReady);
		       }
		       if (sourceData.isRefreshButtonPresent())
		       {
			          mRefresh = menuBar.addItem(menuCommand.messageRefresh, menuCommand);
			          lingMenuMap.put(mRefresh, GeneralWindowCommand.menuRefresh);
			          mRefresh.setEnabled(true);
		       }
			}
		   addMenuBarItemsAtEnd();
		   menuLayout.addComponent(menuBar);
		}
    }
    protected Component getMenuLevel_RightAdjusted_AdditionalComponent()
    {
    	return menuLevel_RightAdjusted_AdditionalComponent;
    }
    protected void createMenuLayout(ResourcePool resource) throws Exception
    {
		menuLayout = new HorizontalLayout();
		menuLayout.setImmediate(false);
		menuLayout.setWidth("100%");
		rootComponents.add(menuLayout);
	    if (isShowAuthorized) this.addComponent(menuLayout);
		createMenuBar(resource,false);
		Component auxComponent=getMenuLevel_RightAdjusted_AdditionalComponent();
		if (auxComponent!=null)
		{
		   menuLayout.addComponent(auxComponent);
		   menuLayout.setComponentAlignment(auxComponent, Alignment.TOP_RIGHT);
		}
    }
    protected void createViewTable(ResourcePool resource) throws Exception
    {
		AETableContainer table = sourceData.getViewTable();
		if (table==null) return;
		Container subContainer = new AESubContainer(table,true,sourceData.getViewColumns());
		viewTable = new Table(null,subContainer);
		leftSideLayout.addComponent(viewTable);
		leftSideLayout.setExpandRatio(viewTable, 1);
		
		viewTable.setImmediate(true);
		viewTable.setVisible(true);
		viewTable.setContainerDataSource(subContainer);
		viewTable.setVisibleColumns(sourceData.getViewColumns());		
		viewTable.setColumnHeaders(sourceData.getTranslatedViewColumnHeaders());	
		viewTable.setColumnCollapsingAllowed(true);
		viewTable.setColumnReorderingAllowed(true);
		viewTable.setSelectable(true);
		viewTable.setStyleName(Runo.TABLE_SMALL);
		viewTable.addStyleName("general_window_view_table"); 
		viewTable.setWidth("100%");
		viewTable.setHeight(sourceData.getDesignTableHeight());
		viewTable.setSortDisabled(false);
		addViewTableSorting();
		addTableHeaderClickListener();
		addTableSelectionListener();
    }
    public void addViewTableSorting()
    {
       String colName= sourceData.getFirstSortColumn();
       boolean colOrder= sourceData.getFirstSortOrder();
       if (colName==null && sourceData.getViewTable()!=null)
       {
    	   colName = sourceData.getViewTable().getFirstSortColumn();
    	   colOrder = sourceData.getViewTable().isFirstSortColumnAscending();
       }
       if (colName!=null)
       {
    	   viewTable.setSortContainerPropertyId(colName);
    	   viewTable.setSortAscending(colOrder);
       }
    }

    protected void containerNewItemSelection(AERawItem item,Object itemId)
    {
    	
    }
    protected void containerClickItemEvent(AERawItem item,String columnName)
    {
    	
    }
    protected void addTableSelectionListener()
    {
    	viewTable.addListener(new Property.ValueChangeListener() {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				
				Property property = event.getProperty();
		        if (property == viewTable) {
		        	Object itemId = viewTable.getValue();
		        	if (itemId!=null)
		        	{
		                AERawItem item =(AERawItem)viewTable.getItem(itemId);
		                if (newEditForm!=null && item != newEditForm.getItemDataSource()
		                		&& newEditPanel.isVisible()) {
		                	  //viewTable.setValue(newEditForm.getItemDataSource());
		            	      //rollback and disableCDPanel();
		                }
		                containerNewItemSelection(item,itemId);
		        	}
		        }
			}
		});
    	viewTable.addListener(new ItemClickEvent.ItemClickListener() {
			
			private static final long serialVersionUID = 7145500828748754484L;

			@Override
			public void itemClick(ItemClickEvent event) {
				AERawItem item =(AERawItem)event.getItem();
				String columnName=(String)event.getPropertyId();
				containerClickItemEvent(item,columnName);
			}
    	});
    			
    }
    protected void createEditButtonLayout(ResourcePool resource) throws Exception
    {
		editButtonLayout = new HorizontalLayout();
		editButtonLayout.setImmediate(true);
		addEditFormSubmitCancelButtons(resource);
		newEditForm.setFooter(editButtonLayout);		
    }
    protected void createNewEditForm(ResourcePool resource) throws Exception
    {
    	boolean formPresent=sourceData.getEditFormFieldAmount()>0;
    	if (!formPresent) return;
	    newEditForm = new Form();
		newEditPanelLayout.addComponent(newEditForm);	
		newEditForm.setValidationVisible(false);
		newEditForm.setValidationVisibleOnCommit(false);
	    newEditForm.setFormFieldFactory(new DefaultFieldFactory(){
		
			private static final long serialVersionUID = 7359753568658330130L;

			@Override
			public Field createField(Item item, Object propertyId,
                    Component uiContext) {
				EditFormField formField = sourceData.getEditColumnHeader(propertyId);
				if (formField==null) return null;
				Field field = formField.getFieldGenerated(item);
				if (field!=null)
				   {
				     field.setWidth(editFieldWidth);
				     return field;
				   }
				field = super.createField(item, propertyId, uiContext);
			    field.setWidth(editFieldWidth);
				field.setVisible(true);
				formField.setCurrentField(field);
				field.setRequired(formField.isRequired());
                field.setCaption(formField.getCaptionName());
                int validamnt=formField.getValidatorAmount();
                for(int i=0;i<validamnt;i++) field.addValidator(formField.getValidator(i));
				if (field instanceof TextField) {
                    ((TextField) field).setNullRepresentation("");
                }
				return field;

			}
		});
	    createEditButtonLayout(resource); 
    }
    protected void addEditFormSubmitCancelButtons(ResourcePool resource) throws Exception
    {
		// bApply
		bApply = new Button();
		bApply.setImmediate(true);
		//bApply.setTabIndex(5);
		editButtonLayout.addComponent(bApply);
		
		// bCancel
		bCancel = new Button();
		bCancel.setImmediate(true);
		editButtonLayout.addComponent(bCancel);
		setCaptionsForNewEditPanelButtons(resource);
		addButtonListeners();
    }
    protected void newItemValidation()
    {
    	
    }
    protected void editItemValidation()
    {
    	
    }
    protected void addTextFiltersForEachColumn(ResourcePool resource) throws Exception 
    {
    	if (!sourceData.isLikeFilterForEachColumnToBeProvided()) return;
		filterBar = new HorizontalLayout();
		filterBar.setWidth("100%");
		leftSideLayout.addComponent(filterBar);
		filterBar.addComponent(new Button("-", new Button.ClickListener() 
		             { 
						private static final long serialVersionUID = 1L;

							public void buttonClick(ClickEvent event) { 
                                    for(int i=0;i<filterTextFields.length;i++)
                                    {
                                    	filterTextFields[i].setValue("");
                                    }
			                  }
		             }));
		filterBar.addComponent(new Button("+", new Button.ClickListener() 
        { 
			private static final long serialVersionUID = 1L;

				public void buttonClick(ClickEvent event) { 
					viewTable.focus();
                 }
        }));
		String[] visibleCols = sourceData.getTranslatedViewColumnHeaders(); 
		int ncols = visibleCols.length;
		filterTextFields = new TextField[ncols];
		for (int i=0;i<ncols;i++) 
		{ 
			final TextField sf = new TextField(); 
			final String pn = visibleCols[i];
			final int pn_no=i;
			filterTextFields[i]=sf;
			filterBar.addComponent(sf); 
			sf.setWidth("100%"); 
			sf.setHeight("30px");
			sf.setInputPrompt(pn); 
			sf.setImmediate(true); 
			filterBar.setExpandRatio(sf, 1); 
			sf.addListener(new Property.ValueChangeListener() 
			{ 
				private static final long serialVersionUID = 1L;

				public void valueChange(Property.ValueChangeEvent event) 
				{ 
					String chng = sf.toString();
					sourceData.updateColumnLikeFilter(pn_no, chng);
				}
			});
		
		}
    }
    protected void addTableHeaderClickListener() throws Exception
    {
    	if (!containerLevelSorting) return;
		viewTable.addListener(new Table.HeaderClickListener() {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void headerClick(HeaderClickEvent event) {
				String s=event.getPropertyId().toString();
				sourceData.getViewTable().addAscendingSortingColumnAtBeginningOrChangeDirection(s);
			}
		});
    }
    protected void addButtonListeners() throws Exception
    {
		bApply.addListener(new Button.ClickListener() {			
			private static final long serialVersionUID = -3143253462555220935L;

			@Override
			public void buttonClick(ClickEvent event) {
				try {
					newEditForm.commit();
					if (!newEditForm.isValid()) {
		                return;
		            }
				}
				catch(com.vaadin.data.Validator.EmptyValueException e)
				{
					getWindow().showNotification(sourceData.getActiveSpecificResource().getTranslation("PleaseFillInAllRequiredFieldsMarkedWithAsterisk"), Notification.TYPE_WARNING_MESSAGE);
					return;
				}
				catch(Exception e)
				{
					System.out.println("Validation: "+e+" message:"+e.getMessage());
		        	getWindow().showNotification(e.getMessage(), Notification.TYPE_WARNING_MESSAGE);
		        	return;
				}
				try {
						if (isNewDocumentAdded)
				       {
				    	if (newEditObjectId==null)
				    	{
				    		throw new RuntimeException("newEditObjectId result is null");
				    	}
				    	 newItemValidation();
				    } else editItemValidation();
				   
				    AERawItem item = (AERawItem)sourceData.getViewTable().getItem(newEditObjectId);
		            sourceData.getViewTable().commit();
		            viewTable.setValue(item);
		        } 
				catch(AEUniqueIndexViolationException e2)
				{
					try {sourceData.getViewTable().rollback();} catch(Exception e1){}
					getWindow().showNotification(menuCommand.messageFieldMustBeUnique,Notification.TYPE_HUMANIZED_MESSAGE);
				}
				catch (Exception e) {
		        	e.printStackTrace();
		        	try {sourceData.getViewTable().rollback();} catch(Exception e1){}
		        	getWindow().showNotification(menuCommand.messageServerError, e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		        }
				disableFormPanel();
			}
		});
		bCancel.addListener(new Button.ClickListener() {			
			
			private static final long serialVersionUID = -6839497274631461435L;

			@Override
			public void buttonClick(ClickEvent event) {
				ensureDisableFormPanel();
			}
		});
    }
}

